package com.thinkit.bigdata.web.controller.perCenter;

import com.google.common.base.Strings;
import com.thinkit.bigdata.core.ConfigHelper;
import com.thinkit.bigdata.core.util.DateFormatUtil;
import com.thinkit.bigdata.core.util.TaskUtil;
import com.thinkit.bigdata.core.util.es.ESUtil;
import com.thinkit.bigdata.core.util.excel.XlsUtil;
import com.thinkit.bigdata.web.controller.pubmet.PubMethod;
import com.thinkit.bigdata.web.coremet.SystemStatic;
import com.thinkit.bigdata.web.model.es.countEs.CountModelRules;
import com.thinkit.bigdata.web.model.es.countEs.CountSource;
import com.thinkit.bigdata.web.model.result.HtmlResult;
import com.thinkit.bigdata.web.service.config.AreaService;
import com.thinkit.bigdata.web.service.perCenter.MyAssService;
import org.apache.log4j.Logger;
import org.apache.lucene.search.join.ScoreMode;
import org.apache.poi.hssf.usermodel.*;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 我的考核Controller
 * Created by hccl on 2018/9/7.
 */
@RestController
@RequestMapping("/my-accessment")
public class MyAssessment {

    private static Logger logger = Logger.getLogger(MyAssessment.class);

    @Resource
    private MyAssService myAssService;

    @Resource
    private AreaService areaService;

    @Resource
    private ESUtil esUtil;

    @RequestMapping(value = "/get-data-list", method = RequestMethod.POST)
    public HtmlResult getDataLists(HttpServletRequest request) {
        String logTxt = "【获取我的考核信息列表】";
        logger.info(logTxt);
        String pageNum = request.getParameter("pageNum");//起始页
        String pageSize = request.getParameter("pageSize");//每页条数
        String sortName = request.getParameter("sortName");//录音流水
        String sortOrder = request.getParameter("sortOrder");//录音流水
        logger.info(logTxt + "pageNum = " + pageNum);
        logger.info(logTxt + "pageSize = " + pageSize);
        logger.info(logTxt + "sortName = " + sortName);
        logger.info(logTxt + "sortOrder = " + sortOrder);
        return myAssService.getDataList(request);
    }

    @RequestMapping(value = "/get-data-list-search", method = RequestMethod.POST)
    public HtmlResult getDataList(HttpServletRequest request) {
        String logTxt = "【获取我的考核任务下拉框数据】";
        logger.info(logTxt);
        try {
            return myAssService.getDataList(request.getParameter("code"));
        } catch (IOException e) {
            e.printStackTrace();
            return HtmlResult.failure("获取数据异常");
        }
    }

    @RequestMapping(value = "/get-data-list-id", method = RequestMethod.POST)
    public HtmlResult getDataListById(HttpServletRequest request) {
        String logTxt = "【获取我的考核信息列表-详情信息】";
        logger.info(logTxt);
        String id = request.getParameter("id");//质检任务名称
        logger.info(logTxt + "id = " + id);
        return myAssService.getDataListById(request);
    }

    @RequestMapping(value = "/get-data-list-count-id", method = RequestMethod.POST)
    public HtmlResult getDataListCountById(HttpServletRequest request) {
        String logTxt = "【获取我的考核-质检结果-命中语音量】";
        logger.info(logTxt);
        String workId = request.getParameter("id");//质检任务名称
        String callStartTime = request.getParameter("callStartTime");//质检考核周期 开始时间
        String callEndTime = request.getParameter("callEndTime");//质检考核周期 结束时间
        String seatId = request.getParameter("seatId");//坐席工号
        logger.info(logTxt + "workId = " + workId);
        logger.info(logTxt + "callStartTime = " + callStartTime);
        logger.info(logTxt + "callEndTime = " + callEndTime);
        logger.info(logTxt + "seatId = " + seatId);
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        if (!Strings.isNullOrEmpty(seatId)) {
            boolQuery.must(QueryBuilders.matchQuery("voiceInfo.seatId", seatId));
        }
        PubMethod.formatTime(boolQuery, callStartTime, callEndTime);
        boolQuery.must(
                QueryBuilders.nestedQuery(
                        "workScores",
                        QueryBuilders.boolQuery()
                                .must(QueryBuilders.matchQuery("workScores.workId", workId))
                                .must(
                                        QueryBuilders.nestedQuery(
                                                "workScores.modelRules",
                                                QueryBuilders.existsQuery("workScores.modelRules.ruleId"),
                                                ScoreMode.None

                                        )
                                ),
                        ScoreMode.None
                )
        );
        int count = SystemStatic.crud.queryQBuilderAllByMes(SystemStatic.AUDIO_ES_INDEX, SystemStatic.AUDIO_ES_TYPE, boolQuery);
        return HtmlResult.success(count);
    }

    @RequestMapping(value = "/get-data-list-mes", method = RequestMethod.POST)
    public HtmlResult getDataListByMes(HttpServletRequest request) {
        String logTxt = "【查询质检结果详情】";
        logger.info(logTxt);
        String workId = request.getParameter("workId");//质检任务名称
        String callStartTime = request.getParameter("callStartTime");//质检考核周期 开始时间
        String callEndTime = request.getParameter("callEndTime");//质检考核周期 结束时间
        String seatId = request.getParameter("seatId");//坐席工号
        String ruleId = request.getParameter("ruleId");//规则ids
        String pageNum = request.getParameter("pageNum");//起始页
        String pageSize = request.getParameter("pageSize");//每页条数
        String sortName = request.getParameter("sortName");//排序字段
        String sortOrder = request.getParameter("sortOrder");//排除方式
        logger.info(logTxt + "sortName = " + sortName);
        logger.info(logTxt + "sortOrder = " + sortOrder);
        logger.info(logTxt + "workId = " + workId);
        logger.info(logTxt + "seatId = " + seatId);
        logger.info(logTxt + "ruleId = " + ruleId);
        logger.info(logTxt + "callStartTime = " + callStartTime);
        logger.info(logTxt + "callEndTime = " + callEndTime);
        logger.info(logTxt + "pageNum = " + pageNum);
        logger.info(logTxt + "pageSize = " + pageSize);
        return myAssService.getDataListByMes(request);
    }

    @RequestMapping(value = "/export-my-ass", method = RequestMethod.POST)
    public void exportMyAss(HttpServletRequest request, HttpServletResponse response) {
        String logTxt = "【获取我的考核信息-导出】";
        logger.info(logTxt);
        String sortName = request.getParameter("sortName");//录音流水
        String sortOrder = request.getParameter("sortOrder");//录音流水
        sortName = sortName == null ? "province" : sortName;
        sortOrder = sortOrder == null ? "asc" : sortOrder;
        logger.info(logTxt + "sortName = " + sortName);
        logger.info(logTxt + "sortOrder = " + sortOrder);
        try {
            BoolQueryBuilder boolQuery = myAssService.getQuery(logTxt, request);
            List<CountSource> countSources = new ArrayList<>();
            //总条数
            Integer sum = SystemStatic.crud.queryQBuilderAllByMes(SystemStatic.COUNT_ES_INDEX, SystemStatic.COUNT_ES_TYPE, boolQuery);
            //单词查询条数
            int excleMax = ConfigHelper.getInt("export.data.sheet.max.number", 1000);
            List<Integer> pageTout = TaskUtil.formatSum(sum, excleMax);//todo最后一个数字需要特殊处理:6022
            for (Integer aPageTout : pageTout) {
                List<String> docList = SystemStatic.crud.queryMapQBuilderList(
                        SystemStatic.COUNT_ES_INDEX,
                        SystemStatic.COUNT_ES_TYPE,
                        aPageTout,
                        excleMax,
                        boolQuery,
                        sortName,
                        sortOrder
                );
                if (docList.isEmpty()) continue;
                countSources.addAll(esUtil.strs2Entitys1(docList));
            }
            logger.info("获取数据条数为：" + countSources.size());
            //生成excel
            HSSFWorkbook workbook = new HSSFWorkbook();//创建一个xls文档对象
            HSSFSheet sheet = workbook.createSheet();//创建一个工作薄对象
            //设置标题和列名称
            String[] header = {"编号", "省份", "质检任务名称", "考核月份", "考核周期",
                    "坐席班组", "坐席工号", "坐席姓名", "得分", "质检话务量"};
            String title = "我的考核信息表";
            XlsUtil.setTableTitleHeader(workbook, sheet, Arrays.asList(header), title);
            //获取表文样式
            HSSFCellStyle tableStyle = XlsUtil.getTableStyle(workbook);
            HSSFRow row2;
            HSSFCell cell2;
            for (int j = 0; j < countSources.size(); j++) {
                CountSource source = countSources.get(j);
                row2 = sheet.createRow(3 + j);
                for (int i = 0; i < header.length; i++) {
                    cell2 = row2.createCell(i);
                    cell2.setCellStyle(tableStyle);
                    switch (i) {
                        case 0:
                            cell2.setCellValue(new HSSFRichTextString((j + 1) + ""));
                            break;
                        case 1:
                            cell2.setCellValue(new HSSFRichTextString(areaService.selectByPrimaryCode(source.getProvince()).getArea()));
                            break;
                        case 2:
                            cell2.setCellValue(new HSSFRichTextString(source.getWorkName()));
                            break;
                        case 3:
                            cell2.setCellValue(new HSSFRichTextString((source.getMonthlyAssess() == null || source.getMonthlyAssess() == 0) ? "-" : source.getMonthlyAssess() + ""));
                            break;
                        case 4:
                            cell2.setCellValue(new HSSFRichTextString(Strings.isNullOrEmpty(source.getCycleAssess()) ? "-" : source.getCycleAssess() + ""));
                            break;
                        case 5:
                            cell2.setCellValue(new HSSFRichTextString(source.getGroupName()));
                            break;
                        case 6:
                            cell2.setCellValue(new HSSFRichTextString(source.getSeatId()));
                            break;
                        case 7:
                            cell2.setCellValue(new HSSFRichTextString(source.getSeatName()));
                            break;
                        case 8:
                            cell2.setCellValue(new HSSFRichTextString(source.getWorkScore() + ""));
                            break;
                        case 9:
                            cell2.setCellValue(new HSSFRichTextString(source.getAudioSum() == null ? "-" : source.getAudioSum().toString()));
                            break;
                    }
                }
            }
            for (int i = 0; i < header.length; i++) {
                sheet.autoSizeColumn((short) i, true);//自动调整列宽
            }
            String fileName = title + "_" + DateFormatUtil.getNowTime() + ".xls";
            // 清空response
            response.reset();
            response.setContentType("application/vnd.ms-excel");
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));  //转码之后下载的文件名不会出现中文乱码
            workbook.write(response.getOutputStream());
        } catch (Exception e) {
            logger.info(logTxt + "异常");
        }
    }

    @RequestMapping(value = "/export-my-ass-res", method = RequestMethod.POST)
    public void exportMyAssRes(HttpServletRequest request, HttpServletResponse response) {
        String logTxt = "【获取我的考核信息列表-详情信息-导出】";
        logger.info(logTxt);
        try {
            String id = request.getParameter("id");//质检任务名称
            logger.info(logTxt + "id = " + id);
            String mgs = SystemStatic.crud.get(SystemStatic.COUNT_ES_INDEX, SystemStatic.COUNT_ES_TYPE, id);
            CountSource source = esUtil.str2entity1(mgs);
            List<CountModelRules> countModelRules =  source.getModelRules();
            //生成excel
            HSSFWorkbook workbook = new HSSFWorkbook();//创建一个xls文档对象
            HSSFSheet sheet = workbook.createSheet();//创建一个工作薄对象
            //设置标题和列名称
            String[] header = {"编号", "质检模型名称", "质检规则名称", "属性",
                    "致命性", "命中语音量", "分值"};
            String title = "我的考核-质检结果信息表";
            XlsUtil.setTableTitleHeader(workbook, sheet, Arrays.asList(header), title);
            //获取表文样式
            HSSFCellStyle tableStyle = XlsUtil.getTableStyle(workbook);
            HSSFRow row2;
            HSSFCell cell2;
            for (int j = 0; j < countModelRules.size(); j++) {
                CountModelRules modelRules = countModelRules.get(j);
                row2 = sheet.createRow(3 + j);
                for (int i = 0; i < header.length; i++) {
                    cell2 = row2.createCell(i);
                    cell2.setCellStyle(tableStyle);
                    switch (i) {
                        case 0:
                            cell2.setCellValue(new HSSFRichTextString((j + 1) + ""));
                            break;
                        case 1:
                            cell2.setCellValue(new HSSFRichTextString(modelRules.getModelName()));
                            break;
                        case 2:
                            cell2.setCellValue(new HSSFRichTextString(modelRules.getRuleName()));
                            break;
                        case 3:
                            cell2.setCellValue(new HSSFRichTextString(modelRules.getUseFor() == 0?"系统":"人工"));
                            break;
                        case 4:
                            cell2.setCellValue(new HSSFRichTextString(esUtil.changeRuleFateFul(modelRules.getFateful())));
                            break;
                        case 5:
                            cell2.setCellValue(new HSSFRichTextString(modelRules.getRuleTimes() + ""));
                            break;
                        case 6:
                            cell2.setCellValue(new HSSFRichTextString(modelRules.getScore() + ""));
                            break;
                    }
                }
            }
            for (int i = 0; i < header.length; i++) {
                sheet.autoSizeColumn((short) i, true);//自动调整列宽
            }
            String fileName = title + "_" + DateFormatUtil.getNowTime() + ".xls";
            // 清空response
            response.reset();
            response.setContentType("application/vnd.ms-excel");
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));  //转码之后下载的文件名不会出现中文乱码
            workbook.write(response.getOutputStream());
        } catch (Exception e) {
            logger.info(logTxt + "异常");
        }
    }
}
